package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * 封装Request对象，需要传入输入流InputStream
 */
public class Request {

    private String method; // 请求方式：比如GET/POST

    private String url; // 请求路径，例如/,/index.html

    private String host; // 请求host

    private String projectName; // 项目名称

    private InputStream inputStream; // 输入流，其他属性从输入流中解析出来

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public Request() {
    }

    public Request(InputStream inputStream) {
        try {
            this.inputStream = inputStream;

            // 获取字节流长度，刚开始可能为空
            int count = 0;
            while (count == 0) {
                count = inputStream.available();
            }
            // 转成字节数组
            byte[] bytes = new byte[count];
            inputStream.read(bytes);

            String requestStr = new String(bytes);
            String[] requestList = requestStr.split("\\n");
            // 获取第一行请求头信息
            String firstLineStr = requestList[0];
            String sendLineStr = requestList[1];
            String[] strings = firstLineStr.split(" ");
            String[] strings1 = sendLineStr.split(":");

            String url = strings[1];
            String project_name = url.substring(1, url.indexOf("/", 1));
            String url1 = url.substring(url.indexOf("/", 1));

            this.projectName = project_name;
            this.url = url1;
            this.method = strings[0];
            this.host = strings1[1].trim();

            System.out.println("=======>>>method：" + method);
            System.out.println("=======>>>url：" + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String url = "/demo/lagou/";
        System.out.println();
        System.out.println(url.substring(url.indexOf("/", 1)));
    }
}
